﻿/**
Core script to handle the entire theme and core functions
**/
var ComApp = function () {

    // initializes main settings
    var handleInit = function () {

        //ajax的loading
        //$(document).ajaxStart(function () {
        //            App.blockUI({animate: true});
        //}).ajaxStop(function () {
        //    App.unblockUI();
        //});

    };
    var handleInitToastr = function () {
        toastr.options = {
            "closeButton": true,//是否显示关闭按钮
            "debug": false,//是否使用debug模式
            "positionClass": "toast-top-center",//弹出窗的位置
            "showDuration": "300",//显示的动画时间
            "hideDuration": "1000",//消失的动画时间
            "timeOut": "5000",//展现时间
            "extendedTimeOut": "1000",//加长展示时间
            "showEasing": "swing",//显示时的动画缓冲方式
            "hideEasing": "linear",//消失时的动画缓冲方式
            "showMethod": "fadeIn",//显示时的动画方式
            "hideMethod": "fadeOut"//消失时的动画方式
        };
    };
    var handleInitBootbox = function () {
        // 设置为中文
        bootbox.setDefaults({ locale: "zh_CN" });

        //       ComApp.bootboxConfirm("你是要更新当前的测试用户吗?", function (result) { });

    };
    var handleSelect2 = function () {

        // Set the "bootstrap" theme as the default theme for all Select2
        // widgets.
        //
        // @see https://github.com/select2/select2/issues/2927
        $.fn.select2.defaults.set("theme", "bootstrap");

        var placeholder = "请选择";

        $(".select2, .select2-multiple").select2({
            placeholder: placeholder,
            language: "zh-CN",
            width: null
        });

        $(".select2-allow-clear").select2({
            allowClear: true,
            placeholder: placeholder,
            width: null
        });

        // @see https://select2.github.io/examples.html#data-ajax
        function formatRepo(repo) {
            if (repo.loading) return repo.text;

            var markup = "<div class='select2-result-repository clearfix'>" +
                "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +
                "<div class='select2-result-repository__meta'>" +
                "<div class='select2-result-repository__title'>" + repo.full_name + "</div>";

            if (repo.description) {
                markup += "<div class='select2-result-repository__description'>" + repo.description + "</div>";
            }

            markup += "<div class='select2-result-repository__statistics'>" +
                "<div class='select2-result-repository__forks'><span class='glyphicon glyphicon-flash'></span> " + repo.forks_count + " Forks</div>" +
                "<div class='select2-result-repository__stargazers'><span class='glyphicon glyphicon-star'></span> " + repo.stargazers_count + " Stars</div>" +
                "<div class='select2-result-repository__watchers'><span class='glyphicon glyphicon-eye-open'></span> " + repo.watchers_count + " Watchers</div>" +
                "</div>" +
                "</div></div>";

            return markup;
        }

        function formatRepoSelection(repo) {
            return repo.full_name || repo.text;
        }

        //$(".js-data-example-ajax").select2({
        //    width: "off",
        //    ajax: {
        //        url: "https://api.github.com/search/repositories",
        //        dataType: 'json',
        //        delay: 250,
        //        data: function (params) {
        //            return {
        //                q: params.term, // search term
        //                page: params.page
        //            };
        //        },
        //        processResults: function (data, page) {
        //            // parse the results into the format expected by Select2.
        //            // since we are using custom formatting functions we do not need to
        //            // alter the remote JSON data
        //            return {
        //                results: data.items
        //            };
        //        },
        //        cache: true
        //    },
        //    escapeMarkup: function (markup) {
        //        return markup;
        //    }, // let our custom formatter work
        //    minimumInputLength: 1,
        //    templateResult: formatRepo,
        //    templateSelection: formatRepoSelection
        //});

        $("button[data-select2-open]").click(function () {
            $("#" + $(this).data("select2-open")).select2("open");
        });

        $(":checkbox").on("click", function () {
            $(this).parent().nextAll("select").prop("disabled", !this.checked);
        });

        // copy Bootstrap validation states to Select2 dropdown
        //
        // add .has-waring, .has-error, .has-succes to the Select2 dropdown
        // (was #select2-drop in Select2 v3.x, in Select2 v4 can be selected via
        // body > .select2-container) if _any_ of the opened Select2's parents
        // has one of these forementioned classes (YUCK! ;-))
        $(".select2, .select2-multiple, .select2-allow-clear, .js-data-example-ajax").on("select2:open", function () {
            if ($(this).parents("[class*='has-']").length) {
                var classNames = $(this).parents("[class*='has-']")[0].className.split(/\s+/);

                for (var i = 0; i < classNames.length; ++i) {
                    if (classNames[i].match("has-")) {
                        $("body > .select2-container").addClass(classNames[i]);
                    }
                }
            }
        });

        $(".js-btn-set-scaling-classes").on("click", function () {
            $("#select2-multiple-input-sm, #select2-single-input-sm").next(".select2-container--bootstrap").addClass("input-sm");
            $("#select2-multiple-input-lg, #select2-single-input-lg").next(".select2-container--bootstrap").addClass("input-lg");
            $(this).removeClass("btn-primary btn-outline").prop("disabled", true);
        });
    }

    var tableScrollOption;
    var handleTable = function () {
        //不能放到MyDatatables中，会有TypeError
        tableScrollOption = {
            //dom常用的初始化字符如下：
            //l - Length changing  选择每页显示行数下拉框的控件
            //f - Filtering input  搜索过滤控件
            //t - The Tabletools    导出excel，csv的按钮
            //i - Information  显示汇总信息（从 1 到 100 /共 1,288 条数据）
            //p - Pagination   分页控件
            //r - pRocessing   显示加载时的进度条
            //C - copy 显示复制，excel的控件
            //下面四种是在dom中在自定义的位置植入自定义元素和class
            //< and > - DIV元素
            //<"class" and > - DIV和Class
            //<"#id" and > - DIV和ID
            //<"#id.class" and > - DIV 和ID 和Class
            // "dom": "ifr<'table-scrollable't>lp",
            "dom": "ifr<'table-scrollable't>",

            //// setup buttons extension: http://datatables.net/extensions/buttons/
            "buttons": [
                // { extend: 'print', className: 'btn default' },
                { extend: 'copy', className: 'btn btn-circle default' },
                // { extend: 'pdf', className: 'btn default' },
                // { extend: 'excel', className: 'btn default' },
                // { extend: 'csv', className: 'btn default' },
                {
                    text: "<i class='icon-reload'></i>",
                    className: "btn btn-circle btn-icon-only btn-default",
                    action: function (e, dt, node, config) {
                        dt.api().fnReloadAjax();
                    }
                }
            ],
            // scroller extension: http://datatables.net/extensions/scroller/
            scrollY: 500,
            deferRender: true,
            scroller: true,
            scrollX: true,
            scrollCollapse: true,
        };
    };

    //* END:CORE HANDLERS *//
    var handleInitDate = function () {
        Date.prototype.format = function (fmt) { //author: meizz   
            var o = {
                "M+": this.getMonth() + 1,                 //月份   
                "d+": this.getDate(),                    //日   
                "h+": this.getHours(),                   //小时   
                "m+": this.getMinutes(),                 //分   
                "s+": this.getSeconds(),                 //秒   
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
                "S": this.getMilliseconds()             //毫秒   
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt))
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }
    };

    var handleInitValidator = function () {
        (function (factory) {
            if (typeof define === "function" && define.amd) {
                define(["jquery", "../jquery.validate"], factory);
            } else {
                factory(jQuery);
            }
        }(function ($) {

            /*
             * Translated default messages for the jQuery validation plugin.
             * Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語)
             */
            $.extend($.validator.messages, {
                required: "这是必填字段",
                remote: "请修正此字段",
                email: "请输入有效的电子邮件地址",
                url: "请输入有效的网址",
                date: "请输入有效的日期",
                dateISO: "请输入有效的日期 (YYYY-MM-DD)",
                number: "请输入有效的数字",
                digits: "只能输入数字",
                creditcard: "请输入有效的信用卡号码",
                equalTo: "你的输入不相同",
                extension: "请输入有效的后缀",
                maxlength: $.validator.format("最多可以输入 {0} 个字符"),
                minlength: $.validator.format("最少要输入 {0} 个字符"),
                rangelength: $.validator.format("请输入长度在 {0} 到 {1} 之间的字符串"),
                range: $.validator.format("请输入范围在 {0} 到 {1} 之间的数值"),
                max: $.validator.format("请输入不大于 {0} 的数值"),
                min: $.validator.format("请输入不小于 {0} 的数值")
            });

        }));
    };

    var handleDatePickers = function () {

        if (jQuery().datepicker) {
            $('.date-picker').datepicker({
                rtl: App.isRTL(),
                language: 'zh-CN',
                orientation: "left",
                clearBtn: true,//清除按钮
                todayBtn: true,//今日按钮
                format: "yyyy-mm-dd",//日期格式
                autoclose: true
            });
            //$('body').removeClass("modal-open"); // fix bug when inline picker is used in modal
        }

        /* Workaround to restrict daterange past date select: http://stackoverflow.com/questions/11933173/how-to-restrict-the-selectable-date-ranges-in-bootstrap-datepicker */
    }

    var handleTimePickers = function () {

        if (jQuery().timepicker) {
            $('.timepicker-default').timepicker({
                autoclose: true,
                showSeconds: true,
                minuteStep: 1
            });

            $('.timepicker-no-seconds').timepicker({
                autoclose: true,
                minuteStep: 5
            });

            $('.timepicker-24').timepicker({
                autoclose: true,
                minuteStep: 5,
                showSeconds: false,
                showMeridian: false
            });

            // handle input group button click
            $('.timepicker').parent('.input-group').on('click', '.input-group-btn', function (e) {
                e.preventDefault();
                $(this).parent('.input-group').find('.timepicker').timepicker('showWidget');
            });
        }
    }


    var handleDatetimePicker = function () {

        if (!jQuery().datetimepicker) {
            return;
        }

        $(".form_datetime").datetimepicker({
            autoclose: true,
            isRTL: App.isRTL(),
            format: "dd MM yyyy - hh:ii",
            pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left")
        });

        $(".form_advance_datetime").datetimepicker({
            isRTL: App.isRTL(),
            format: "dd MM yyyy - hh:ii",
            autoclose: true,
            todayBtn: true,
            startDate: "2013-02-14 10:00",
            pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
            minuteStep: 10
        });

        $(".form_meridian_datetime").datetimepicker({
            isRTL: App.isRTL(),
            format: "dd MM yyyy - HH:ii P",
            showMeridian: true,
            autoclose: true,
            pickerPosition: (App.isRTL() ? "bottom-right" : "bottom-left"),
            todayBtn: true
        });

        $('body').removeClass("modal-open"); // fix bug when inline picker is used in modal
    }


    return {

        //main function to initiate the theme
        init: function () {
            //Core handlers
            handleInit(); // initialize core variables
            handleInitToastr(); // 初始化Toastr
            handleInitBootbox(); // 初始化Bootbox
            handleSelect2(); // 初始化Select2
            handleTable(); // 初始化table
            handleInitDate(); //初始化date格式
            handleInitValidator();

            handleDatePickers();
            handleTimePickers();
            handleDatetimePicker();

        },
        messageWarning: function (message) {
            toastr.warning(message);

        },
        messageSuccess: function (message) {
            toastr.success(message);

        },
        messageError: function (message) {
            toastr.error(message);
        },
        messageInfo: function (message) {
            toastr.info(message);
        },
        //绑定字典内容到指定的Select控件
        bindSelect2: function (ctrlId, url) {
            var control = $("#" + ctrlId);
            //绑定Ajax的内容
            $.getJSON(url, function (data) {
                control.empty(); //清空下拉框
                $.each(data, function (i, item) {
                    control.append("<option value='" + item.id + "'>" + item.text + "</option>");
                });
                control.change(); //告诉select2代码已经更新，需要重载
            });
        },
        Pulsate: function (ctrlId) {
            if (!jQuery().pulsate) {
                return;
            }

            if (App.isIE8() === true) {
                return; // pulsate plugin does not support IE8 and below
            }

            if (jQuery().pulsate) {
                $(ctrlId).pulsate({
                    color: "#fdbe41",
                    reach: 50,
                    repeat: 10,
                    speed: 100,
                    glow: true
                });
            }
        },
        setFormCtrlByArray: function (id, obj) {
            //得到附件字段相关的信息
            var docNameListStr = obj.DocNameList;
            var docNameList = [];
            if (docNameListStr) {
                docNameList = JSON.parse(docNameListStr);
            }
            //循环
            for (var attr in obj) { //通过for in遍历对象的所有属性值

                var newValue = obj[attr];

                if (typeof (newValue) == 'function') { //判断属性类型，必须不是function类型的属性，才能赋值到表单上              
                    continue;
                }
                if (newValue == null) {
                    newValue = "";
                }

                var $input = $("#" + id + " :input[name='" + attr + "']"); //取的对应form下的对应表单
                var type = $input.attr("type"); //获取当前遍历表单的类型                
                if (type === "checkbox" || type === "radio") { //如果是单选或者双选就需要处理   
                    var avalues = String(newValue).split(","); //根据
                    //清空选项
                    $input.each(function (i, n) {
                        if ($(n).hasClass('icheck')) {
                            $(n).iCheck('uncheck'); //.prop("checked", true); //设置选中项
                        } else {
                            $(n).prop("checked", false); //设置选中项
                        }
                    });

                    //设置选项值
                    for (var v = 0; v < avalues.length; v++) {
                        $input.each(function (i, n) { //通过jquery的each遍历这种单选或者双选的每一个选项
                            var value = $(n).val();
                            if (value === avalues[v]) {
                                if ($(n).hasClass('icheck')) {
                                    $(n).iCheck('check'); //.prop("checked", true); //设置选中项

                                } else {
                                    $(n).prop("checked", true); //设置选中项
                                }
                            }
                        });
                    }
                } else { //为类型为type直接赋值
                    if ($input.parent('.date').hasClass('date-picker')) {
                        if (newValue !== "") {
                            var dates = new Date(parseInt(newValue.slice(6)));
                            $input.parent('.date').datepicker("setDate", dates); //设置
                        } else {
                            $input.parent('.date').datepicker("setDate", ""); //设置
                        }
                    } else if ($input.hasClass('rbacwf-CtrlType-FileGroup')) {//如果是附件控件类型
                        $input.val(newValue);
                        if (newValue !== "") {
                            var showStr = docNameList[newValue].join(',');
                            var $inputShow = $("#" + id + " :input[name='" + attr + "_FileGroupShow']"); //取的对应form下的对应表单
                            $inputShow.val(showStr);
                        }
                    } else {
                        if (newValue.toString().indexOf("/Date(") === 0) {
                            $input.val(new Date(parseInt(newValue.slice(6))).format("yyyy-MM-dd hh:mm:ss"));
                        } else {
                            $input.val(newValue);

                        }
                    }

                }
                //select
                var $select = $("#" + id + " select[name='" + attr + "']"); //取的对应form下的对应表单
                $select.val(newValue);
            }
        },
        updateMenuState: function (url) {
            var $selItemId = $("[href='" + url + "']");

            if ($selItemId) {

                var $parents = $selItemId.parents(".nav-item");

                $parents.addClass("active").addClass("open");

                var $parentsToggle = $parents.children("a.nav-toggle");

                $parentsToggle.children("span.arrow").addClass("open");

                $parentsToggle.append("<span class='selected'></span>");
            }

        },

        bootboxConfirm: function (m, c, t) {
            bootbox.confirm({
                buttons: {
                    confirm: {
                        label: '确定',
                        className: 'btn btn-default'
                    },
                    cancel: {
                        label: '取消',
                        className: 'btn btn-default'
                    }
                },
                message: m,
                callback: c,
                title: t ? t : '请确认',
            });

        },

        bootboxAlert: function (m, c, t) {
            bootbox.alert({
                buttons: {
                    ok: {
                        label: '确定',
                        className: 'btn btn-default'
                    }
                },
                message: m,
                callback: c,
                title: t,
            });
        },
        ajaxPost: function (url, ajaxData, callback, divId) {

            if (divId) {
                App.blockUI({ target: "#" + divId, animate: true });
            } else {
                App.blockUI({ animate: true });

            }

            $.post(url, ajaxData, function (msg) {
                if (divId) {
                    App.unblockUI("#" + divId);
                } else {
                    App.unblockUI();

                }
                if (callback) {
                    callback(msg);

                }
            });
        },
        ajaxGet: function (url, ajaxData, callback, divId) {
            if (divId) {
                App.blockUI({ target: "#" + divId, animate: true });
            } else {
                App.blockUI({ animate: true });

            }

            $.get(url, ajaxData, function (msg) {
                if (divId) {
                    App.unblockUI("#" + divId);
                } else {
                    App.unblockUI();

                }
                if (callback) {
                    callback(msg);

                }
            });
        },
        setAjaxLoading: function (id) {
            if (id) {
                var idd = "#" + id;
                $(idd).ajaxStart(function () {
                    App.blockUI({
                        target: idd,
                        animate: true
                    });
                }).ajaxStop(function () {
                    App.unblockUI(idd);
                });
            } else {
                //ajax的loading
                $(document).ajaxStart(function () {
                    App.blockUI({
                        animate: true
                    });
                }).ajaxStop(function () {
                    App.unblockUI();
                });
            }

        },
        formValidation: function (modalFormId, rules1, callback) {

            var form = $('#' + modalFormId);
            var error = $('.alert-danger', form);
            var success = $('.alert-success', form);

            form.validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-block help-block-error', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "", // validate all fields including form hidden input
                rules: rules1,

                invalidHandler: function (event, validator) { //display error alert on form submit              
                    success.hide();
                    error.show();
                    App.scrollTo(error, -200);
                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
                        .closest('.form-group').addClass('has-error'); // set error class to the control group
                },

                unhighlight: function (element) { // revert the change done by hightlight
                    $(element)
                        .closest('.form-group').removeClass('has-error'); // set error class to the control group
                },

                success: function (label) {
                    label
                        .closest('.form-group').removeClass('has-error'); // set success class to the control group
                },

                submitHandler: function (form) {
                    success.show();
                    error.hide();
                    callback();
                    success.hide();
                }

            });
        },
    };

}();

var ComFuncDt = function () {
    var tableScrollOption = {
        //dom常用的初始化字符如下：
        //l - Length changing  选择每页显示行数下拉框的控件
        //f - Filtering input  搜索过滤控件
        //t - The Tabletools    导出excel，csv的按钮
        //i - Information  显示汇总信息（从 1 到 100 /共 1,288 条数据）
        //p - Pagination   分页控件
        //r - pRocessing   显示加载时的进度条
        //C - copy 显示复制，excel的控件
        //下面四种是在dom中在自定义的位置植入自定义元素和class
        //< and > - DIV元素
        //<"class" and > - DIV和Class
        //<"#id" and > - DIV和ID
        //<"#id.class" and > - DIV 和ID 和Class
        // "dom": "ifr<'table-scrollable't>lp",
        "dom": "ifr<'table-scrollable't>",

        //// setup buttons extension: http://datatables.net/extensions/buttons/
        "buttons": [
            // { extend: 'print', className: 'btn default' },
            { extend: 'copy', className: 'btn btn-circle default' },
            // { extend: 'pdf', className: 'btn default' },
            // { extend: 'excel', className: 'btn default' },
            // { extend: 'csv', className: 'btn default' },
            {
                text: "<i class='icon-reload'></i>",
                className: "btn btn-circle btn-icon-only btn-default",
                action: function (e, dt, node, config) {
                    dt.api().fnReloadAjax();
                }
            }
        ],
        "processing": true, //加载中
        // scroller extension: http://datatables.net/extensions/scroller/
        scrollY: 500,
        deferRender: true,
        scroller: true,
        scrollX: true,
        scrollCollapse: true,

        onSuccess: function (grid, response) {
            // grid:        grid object
            // response:    json object of server side ajax response
            // execute some code after table records loaded
            ComApp.messageInfo("onSuccess");
        },
        onError: function (grid) {
            // execute some code on network or other general error  
        },
        onDataLoad: function (grid) {
            // execute some code on ajax data load
            ComApp.messageInfo("onDataLoad");

        },
    };

    return {
        bindDataTable: function (tableId, option, hasScroll) {

            var tableObj = $("#" + tableId);
            var table;

            //如果使用Ajax，则增加blockUI处理
            if (option.ajax) {
                var ajaxOp = {
                    complete: function (data, type) {
                        App.unblockUI("#" + tableId);
                    },
                    beforeSend: function (data) {
                        App.blockUI({
                            target: "#" + tableId,
                            animate: true
                        });
                        return true;
                    },
                };
                option.ajax = $.extend({}, ajaxOp, option.ajax);
            }

            if (hasScroll) {
                var result = $.extend({}, tableScrollOption, option);
                table = tableObj.dataTable(result);

            } else {

                table = tableObj.dataTable(option);
            }

            //更新checkbox
            function updateCheckbox() {
                var set = "#" + tableId + " .checkboxes";
                jQuery(set).each(function () {
                    var checked = $(this).parents('tr').hasClass('active');
                    if (checked) {
                        $(this).prop("checked", true);
                    } else {
                        $(this).prop("checked", false);
                    }
                });
                jQuery.uniform.update(set);
            }


            //全选按钮
            tableObj.find('.group-checkable').change(function () {
                var checked = jQuery(this).is(":checked");
                //全选,使用这个方式，不触发事件
                if (checked) {
                    $("#" + tableId + ' tbody tr').addClass('active');
                } else {
                    $("#" + tableId + ' tbody tr').removeClass('active');
                }

                updateCheckbox();

            });
            //checkbox单击
            //tableObj.on('change', 'tbody tr .checkboxes', function () {
            //    $(this).parents('tr').toggleClass("active");
            //});

            //checkbox单击
            tableObj.on('click', 'tbody tr', function () {
                $(this).toggleClass("active");
                updateCheckbox();
            });

            return table;
        },
        getSelectDatas: function (tableId) {
            var table = $('#' + tableId).dataTable();
            var nTrs = table.fnGetNodes(); //fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象  

            var rowdata = new Array();
            for (var i = 0; i < nTrs.length; i++) {
                if ($(nTrs[i]).hasClass('active')) {
                    rowdata.push(table.fnGetData(nTrs[i]));
                }
            }

            return rowdata;
        },
        getAllDatas: function (tableId) {
            var table = $('#' + tableId).dataTable();
            var nTrs = table.fnGetNodes(); //fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象  

            var rowdata = new Array();
            for (var i = 0; i < nTrs.length; i++) {
                rowdata.push(table.fnGetData(nTrs[i]));
            }

            return rowdata;
        },
        //根据行数据中的RowId查找数据
        getRowDataByDataRowId: function (tableId, id) {
            var table = $('#' + tableId).dataTable();
            var nTrs = table.fnGetNodes(); //fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象  

            var rowdata = new Array();
            for (var i = 0; i < nTrs.length; i++) {
                var rowData = table.fnGetData(nTrs[i]);
                if (rowData.RowId === id) {
                    return rowData;
                }
            }

            return rowdata;
        },
        //根据Datatable自已有Row的Index查找数据
        getRowDataByRowId: function (tableId, index) {
            var table = $('#' + tableId).dataTable();
            var nTrs = table.fnGetNodes(); //fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象  

            var rowdata = table.fnGetData(nTrs[index]);

            return rowdata;
        },
        reload: function (tableId) {
            var oTable = $('#' + tableId).dataTable();
            oTable.api().ajax.reload();
        },
        initDetailTableData: function (tableId, dataArr) { //dataArr是表格数据数组，和初始化配置需一样的结构
            var table = $('#' + tableId).dataTable();
            var oSettings = table.fnSettings(); //这里获取表格的配置
            table.fnClearTable(this); //动态刷新关键部分语句，先清空数据

            if (dataArr == null) {
                return;
            }

            for (var i = 0, l = dataArr.length; i < l; i++) {
                table.oApi._fnAddData(oSettings, dataArr[i]); //这里添加一行数据
            }
            oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
            table.fnDraw(); //绘制表格
        },
        dataTableColRender: function (colType) {
            switch (colType) {
                case 'DateTime':
                    return function (data, type, row) {
                        if (data) {
                            return new Date(parseInt(data.slice(6))).format("yyyy-MM-dd hh:mm:ss");
                        } else {
                            return data;
                        }

                    }

                default:
                    return null;
            }
        },
    };
}();

var ComFuncJstree = function () {
    var setJstreeNode = function (item) {
        if (item.parent === "#") {
            item.icon = "fa fa-home";
        } else {
            var tagClass = "fa fa-question-circle";
            switch (item.Current.FuncType) {
                case 0://MODULE
                    tagClass = "fa fa-cube";
                    break;
                case 1://UI
                    tagClass = "fa fa-file";
                    break;
                case 2://FUNCITEM
                    tagClass = "fa fa-coffee";
                    break;
                case 3://Unkown
                    tagClass = "fa fa-question-circle";
                    break;
            }
            //根据类型设置图标
            var classT;
            var text;
            switch (item.Current.FuncControlType) {
                case 1://Enable
                    item.icon = tagClass + " icon-state-danger";
                    classT = "label-danger";
                    text = "可用";
                    break;
                case 0://Visible
                    item.icon = tagClass + " icon-state-warning";
                    classT = "label-warning";
                    text = "可见";
                    break;
                case 2://Hide
                    item.icon = tagClass + " icon-state-default";
                    classT = "label-default";
                    text = "隐藏";
                    break;
                default:
                    item.icon = tagClass;
                    classT = "label-default";
                    text = "";
                    break;
            }
            item.text = "<span class='label label-sm " + classT + "'> " + text + "</span><span>&nbsp;&nbsp;&nbsp;" + item.Current.FuncName + "</span>";
        }
    }
    return {
        //以指定的Json数据，初始化JStree控件
        //treeName为树div名称，url为数据源地址，checkbox为是否显示复选框，loadedfunction为加载完毕的回调函数
        bindJsTree2: function (treeId, url, checkbox, loadedfunction) {
            var control = $('#' + treeId);
            control.data('jstree', false); //清空数据，必须

            var isCheck = arguments[2] || false; //设置checkbox默认值为false
            if (isCheck) {
                //复选框树的初始化
                $.getJSON(url, function (data) {
                    control.jstree({
                        'plugins': ["checkbox", "search"], //出现选择框
                        'core': {
                            'check_callback': true,
                            'data': data,
                            "themes": {
                                "dots": true,
                                "responsive": false
                            }
                        }
                    }).bind('loaded.jstree', loadedfunction);
                });
            } else {
                //普通树列表的初始化
                $.getJSON(url, function (data) {
                    control.jstree({
                        "multiple": false,
                        'core': {
                            'check_callback': true,
                            'data': data,
                            "themes": {
                                "responsive": false,
                                "dots": true,
                            }
                        }
                    }).bind('loaded.jstree', loadedfunction);
                });
            }
        },
        bindJsTree: function (treeId, url, checkbox, loadedfunction) {
            var control = $('#' + treeId);
            control.data('jstree', false); //清空数据，必须
            var isCheck = arguments[2] || false; //设置checkbox默认值为false
            if (isCheck) {
                control.jstree({
                    'plugins': ["checkbox", "search"], //出现选择框
                    'core': {
                        'check_callback': true,
                        'data': {
                            "url": url,
                            "dataType": "json"
                        },
                        "themes": {
                            "dots": true,
                            "responsive": false
                        }
                    }
                }).bind('loaded.jstree', loadedfunction);
                //复选框树的初始化
            } else {
                //普通树列表的初始化
                control.jstree({
                    "multiple": false,
                    'core': {
                        'check_callback': true,
                        'data': {
                            "url": url,
                            "dataType": "json"
                        },
                        "themes": {
                            "responsive": false,
                            "dots": true,
                        }
                    }
                }).bind('loaded.jstree', loadedfunction);
            }

        },
        refreshJsTree: function (treeId, loadedfunction) {
            var control = $('#' + treeId);
            control.data('jstree', false); //清空数据，必须

            //临时保存数据
            var data = control.jstree('get_json');

            var isCheck = arguments[2] || false; //设置checkbox默认值为false
            if (isCheck) {
                //复选框树的初始化
                control.jstree({
                    'plugins': ["checkbox", "search"], //出现选择框
                    'core': {
                        'data': data,
                        "themes": {
                            "responsive": false
                        }
                    }
                }).bind('loaded.jstree', loadedfunction);

            } else {
                //普通树列表的初始化
                control.jstree({
                    "multiple": false,
                    'core': {
                        'data': data,
                        "themes": {
                            "responsive": false
                        }
                    }
                }).bind('loaded.jstree', loadedfunction);
            }
        },
        //加载Rbac权限树
        bindJsTreeRbacFunc: function (treeId, url, loadedfunction) {
            var control = $('#' + treeId);
            control.data('jstree', false); //清空数据，必须

            $.getJSON(url, function (datas) {
                for (var i = 0; i < datas.length; i++) {
                    var item = datas[i];
                    //根节点
                    setJstreeNode(item);
                }

                control.jstree({
                    "multiple": false,
                    'core': {
                        'check_callback': true,
                        'data': datas,
                        "themes": {
                            "responsive": false,
                            "dots": true,
                        }
                    }
                }).bind('loaded.jstree', loadedfunction);

            });
        },
        updateNodeJsTree: function (treeId, data) {
            var $treeId = $('#' + treeId);
            var sNodeU = $treeId.jstree('get_node', data.id);
            if (sNodeU) {
                sNodeU.original = data;
            }
            var res = $treeId.jstree('rename_node', sNodeU, sNodeU.original.text);
            var res1 = $treeId.jstree('set_icon', sNodeU, sNodeU.original.icon);
            return res && res1;
        },
        addNodeJsTree: function (treeId, parentNode, childData) {
            var $treeId = $('#' + treeId);
            var res = $treeId.jstree('create_node', parentNode, childData, "last");

            return res;
        },
        getSelectNode: function (treeId) {
            var sels = $('#' + treeId).jstree(true).get_selected(true);
            var ref = null;
            if (sels && sels.length > 0) {
                ref = sels[0];

            }
            return ref;
        },
        getNodeById: function (treeId, id) {
            var sNode = $('#' + treeId).jstree('get_node', id);
            return sNode;
        },
        getSelectNodes: function (treeId) {
            var ref = $('#' + treeId).jstree(true).get_selected(true);
            return ref;
        },
        setJstreeNodeForRbacFunc: function (item) {
            setJstreeNode(item);
        },
        updateNodeForRbacFunc: function (treeId, data) {
            var $treeId = $('#' + treeId);

            var sNodeU = $treeId.jstree('get_node', data.FuncTreeNo);
            if (sNodeU) {
                sNodeU.original.Current = data;
            }
            setJstreeNode(sNodeU.original);
            var res = $treeId.jstree('rename_node', sNodeU, sNodeU.original.text);
            var res1 = $treeId.jstree('set_icon', sNodeU, sNodeU.original.icon);

        },
        addNodeForRbacFunc: function (treeId, parentNode, childData) {
            var $treeId = $('#' + treeId);

            var item = new Object();
            item.parent = parentNode.original.Current.FuncTreeNo;
            item.id = childData.FuncTreeNo;
            item.Current = childData;

            setJstreeNode(item);

            $treeId.jstree('create_node', parentNode, item, "last");

        },
        getChildDatasForRbacFunc: function (treeId, parentNode) {
            var $treeId = $('#' + treeId);

            var dataset = new Array();
            for (var i in parentNode.children) {
                var sNode = $treeId.jstree('get_node', parentNode.children[i]);
                dataset.push(sNode.original.Current);
            }

            return dataset;

        },
        openNode: function (treeId, level, rootId) {

            var $treeId = $('#' + treeId);;

            $treeId.jstree('open_node', rootId);
            var sNode = $treeId.jstree('get_node', rootId);
            if (level >= 0) {
                for (var i in sNode.children) {
                    ComFuncJstree.openNode(treeId, level - 1, sNode.children[i]);
                }

            }

        },
        selectNode: function (treeId, id, isOpen) {

            var $treeId = $('#' + treeId);
            var ret = $treeId.jstree('select_node', id);
            if (isOpen) {
                $treeId.jstree('open_node', id);
            }
            return ret;

        },
        deleteNode: function (treeId, id) {

            var $treeId = $('#' + treeId);
            var sNode = $treeId.jstree('get_node', id);
            var ret = $treeId.jstree('delete_node', sNode);

            return ret;

        }
    };
}();

jQuery(document).ready(function () {
    ComApp.init();
});